package com.hadoop.mr.join;

import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

import java.io.IOException;

/**
 * <p></p>
 *
 * @author Andy
 * @date 2017/10/21
 */
public class MapReduceJoin {

    static class MapperClass extends Mapper<LongWritable, Text, Text, Text> {

        private Text outKey = new Text();
        private Text outVal = new Text();
        private String[] keyValues = null;

        @Override
        protected void map(LongWritable inKey, Text inVal, Context context) throws IOException, InterruptedException {
            keyValues = inVal.toString().split(",",2);
            this.outKey.set(keyValues[0]);
            this.outVal.set(keyValues[1]);
            context.write(this.outKey,this.outVal);
        }
    }

    static class ReduceClass extends Reducer<Text, Text, Text, Text> {
        private Text outVal = new Text();

        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            StringBuilder builder = new StringBuilder();
            for (Text val : values) {
                builder.append(val);
                builder.append(",");
            }

            if (StringUtils.isNotBlank(builder.toString())) {
                outVal.set(builder.deleteCharAt(builder.length()-1).toString());
                context.write(key,outVal);
            }
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);

        job.setJarByClass(MapReduceJoin.class);
        job.setMapperClass(MapperClass.class);
        job.setReducerClass(ReduceClass.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);

        Path outputPath = new Path(args[1]);
        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, outputPath);
        outputPath.getFileSystem(conf).delete(outputPath, true);

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
